//
//  NewsListController.swift
//  SCA
//
//  Created by tjun on 2025/9/14.
//

import UIKit

class NewsListController: BaseController {
    
    let type: NewsType
    
    private var datas: [NewsListModel] = []
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.backgroundColor = AppStyle.color.background
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 150
        tableView.contentInsetAdjustmentBehavior = .never;
        tableView.register(NewsListCell.self, forCellReuseIdentifier: NewsListCell.identifier)
        return tableView
    }()
    
    init(type: NewsType) {
        self.type = type
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .random
        
        tableView.addTo(view)
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        NewsService.loadNewsListData(type: type) { models in
            self.datas.append(contentsOf: models)
            self.tableView.reloadData()
        }
    }
    
    override var hiddenNavigationBar: Bool {
        return true
    }

}

extension NewsListController: UITableViewDataSource, UITableViewDelegate {
 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NewsListCell.identifier, for: indexPath) as! NewsListCell
        let model = datas[indexPath.row]
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let model = datas[indexPath.row]
        let detailController = NewsDetailController(model: model)
        present(detailController, animated: true)
    }
    
}


